package xyz.zhouzhaodong.crm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.zhouzhaodong.crm.dto.ExpensesDto;
import xyz.zhouzhaodong.crm.entity.Expenses;
import xyz.zhouzhaodong.crm.mapper.ExpensesMapper;
import xyz.zhouzhaodong.crm.service.IExpensesService;
import xyz.zhouzhaodong.crm.util.RestMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 费用支出 服务实现类
 * </p>
 *
 * @author zhouzhaodong
 * @since 2020-07-03
 */
@Service
public class ExpensesServiceImpl extends ServiceImpl<ExpensesMapper, Expenses> implements IExpensesService {

    @Resource
    ExpensesMapper expensesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage addExpenses(Expenses expenses) {
        try {
            // 新增
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            expenses.setId(id);
            expenses.setCreateUser(expenses.getStaffId());
            expenses.setCreateTime(new Date());
            expensesMapper.insert(expenses);
            return RestMessage.success(id);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage deleteExpenses(Expenses expenses) {
        try {
            Expenses p = new Expenses();
            p.setId(expenses.getId());
            p.setFlag(1);
            p.setUpdateUser(expenses.getStaffId());
            p.setUpdateTime(new Date());
            expensesMapper.updateById(p);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage updateExpenses(Expenses expenses) {
        try {
            expenses.setUpdateUser(expenses.getStaffId());
            expenses.setUpdateTime(new Date());
            expenses.setStaffId(null);
            expensesMapper.updateById(expenses);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    public RestMessage selectExpenses(ExpensesDto expensesDto) {
        Page<ExpensesDto> page = new Page<>(expensesDto.getPageNo(),
                expensesDto.getPageSize() == 0 ? 10 : expensesDto.getPageSize());
        if(expensesDto.getFlag() == null){
            expensesDto.setFlag(0);
        }
        IPage<ExpensesDto> list = expensesMapper.selectExpenses(expensesDto, page);
        return RestMessage.success(list);
    }

}
